<!--
 * @Author: zgx 2324461523@qq.com
 * @Date: 2024-03-02 15:55:18
 * @LastEditors: zgx 2324461523@qq.com
 * @LastEditTime: 2024-03-03 17:01:30
 * @FilePath: \tph_shop\src\pagesOrder\list\list.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <view class="viewport">
    <!-- tabs -->
    <view class="tabs">
      <text
        class="item"
        v-for="item in orderTabs"
        :key="item.orderState"
        @click="changeCurrentIndex(item.orderState)"
      >
        {{ item.title }}
      </text>
      <!-- 游标 -->
      <view class="cursor" :style="{ left: currentIndex * 20 + '%' }"></view>
    </view>
    <!-- 滑动容器 -->
    <swiper
      class="swiper"
      :style="{ paddingBottom: safeAreaInsets?.bottom + 'px' }"
      :current="currentIndex"
      @change="onChange"
      @animationfinish="onAnimationfinish"
    >
      <!-- 滑动项 -->
      <swiper-item v-for="item in orderTabs" :key="item.orderState">
        <!-- 订单列表 -->
        <scroll-view
          scroll-y
          class="orders"
          refresher-enabled
          :refresher-triggered="item.trigger"
          :refresher-threshold="0"
          @scrolltolower="onScrolltolower"
          @refresherrefresh="onRefresherrefresh"
        >
          <view class="card" v-for="item in orderList" :key="item.id">
            <!-- 订单信息 -->
            <view class="status">
              <text class="date">{{ item.createTime }}</text>
              <!-- 订单状态文字 -->
              <text>{{ item.orderStateText }}</text>
              <!-- 待评价/已完成/已取消 状态: 展示删除订单 -->
              <text
                @click="deleteOrder(item.id)"
                class="icon-delete"
                v-if="item.orderState === 4 || item.orderState === 5 || item.orderState === 6"
              ></text>
            </view>
            <!-- 商品信息，点击商品跳转到订单详情，不是商品详情 -->
            <navigator
              v-for="sku in item.skus"
              :key="sku.id"
              class="goods"
              :url="`/pagesOrder/orderDetail/orderDetail?id=${item.id}`"
              hover-class="none"
            >
              <view class="cover">
                <image mode="widthFix" :src="sku.image" style="width: 200rpx"></image>
              </view>
              <view class="meta">
                <view class="name ellipsis">{{ sku.name }}</view>
                <view class="type">{{ sku.attrsText }}</view>
              </view>
            </navigator>
            <!-- 支付信息 -->
            <view class="payment">
              <text class="quantity">共{{ item.totalNum }}件商品</text>
              <text>实付</text>
              <text class="amount">
                <text class="symbol">¥</text>{{ parseFloat(item.totalMoney).toFixed(2) }}</text
              >
            </view>
            <!-- 订单操作按钮 -->
            <view class="action">
              <!-- 待付款状态：显示去支付按钮 -->
              <template v-if="item.orderState === 1">
                <view class="button primary" @click="goPayment(item.id)">去支付</view>
              </template>
              <template v-else>
                <navigator
                  class="button secondary"
                  :url="`/pagesOrder/create/create?orderId=${item.id}`"
                  hover-class="none"
                >
                  再次购买
                </navigator>
                <!-- 待收货状态: 展示确认收货 -->
                <view
                  v-if="item.orderState === 3"
                  class="button primary"
                  @click="ConfirmReceipt(item.id)"
                  >确认收货</view
                >
              </template>
            </view>
          </view>
          <!-- 底部提示文字 -->
          <view class="loading-text">
            {{ tipText }}
          </view>
        </scroll-view>
      </swiper-item>
    </swiper>
  </view>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import { onShow, onLoad } from '@dcloudio/uni-app'
import {
  getWxPayAPI,
  getMockPayAPI,
  getOrderListAPI,
  putConfirmReceiptAPI,
  deleteOrderAPI,
  cancelOrderAPI,
} from '@/api/order'
import type { orderInfoType } from '@/types/order'
// 获取屏幕边界到安全区域距离
const { safeAreaInsets } = uni.getSystemInfoSync()
// tabs 数据
const orderTabs = ref([
  { orderState: 0, title: '全部', trigger: false },
  { orderState: 1, title: '待付款', trigger: false },
  { orderState: 2, title: '待发货', trigger: false },
  { orderState: 3, title: '待收货', trigger: false },
  { orderState: 4, title: '待评价', trigger: false },
])
// 接收传过来的参数
const query = defineProps<{
  type: number
}>()
// 底部提示文字
const tipText = ref('正在加载...')
// 当前页
const page = ref(1)
// 每页大小
const pageSize = ref(5)
// 总页数
const pages = ref(2)
// 订单列表数据
const orderList = ref<orderInfoType[]>([] as orderInfoType[])
// 获取订单列表数据的函数
const getOrderListData = async (page1: number, current: number) => {
  const res = await getOrderListAPI(page1, pageSize.value, current)
  if (res.code === '1') {
    // 赋值
    if (Number(res.result.page) > 1) {
      orderList.value.push(...res.result.items)
    } else {
      orderList.value = res.result.items
    }
    // 总页数
    pages.value = Number(res.result.pages) as number
    // 当前页
    page.value = Number(res.result.page) as number
    orderList.value.forEach((item) => {
      if (item.orderState === 1) {
        item.orderStateText = '待付款'
      } else if (item.orderState === 2) {
        item.orderStateText = '待发货'
      } else if (item.orderState === 3) {
        item.orderStateText = '待收货'
      } else if (item.orderState === 4) {
        item.orderStateText = '待评价'
      } else if (item.orderState === 5) {
        item.orderStateText = '已完成'
      } else {
        item.orderStateText = '已取消'
      }
    })
    if (Number(res.result.counts) < Number(res.result.pageSize)) {
      tipText.value = '到底啦~'
    } else {
      tipText.value = '正在加载...'
    }
  }
}
// 当前滑块的下标
const currentIndex = ref(0)
// 滑动触发的回调
const onChange = (e: any) => {
  tipText.value = '正在加载...'
  temp = 1
  orderList.value = []
  page.value = 1
  currentIndex.value = e.detail.current
}
let temp = 1
// 滚动到底部的回调
const onScrolltolower = () => {
  temp++
  if (temp <= pages.value) {
    tipText.value = '正在加载...'
    // 还有数据可以加载
    // 继续调用接口函数
    getOrderListData(temp, currentIndex.value)
  } else {
    tipText.value = '到底啦~'
  }
}
const onAnimationfinish = (e: any) => {
  getOrderListData(page.value, e.detail.current)
}
const onRefresherrefresh = async () => {
  orderTabs.value[currentIndex.value].trigger = true
  page.value = 1
  await Promise.all([getOrderListData(page.value, currentIndex.value)])
  orderTabs.value[currentIndex.value].trigger = false
}
// 支付按钮的回调
const goPayment = async (id: string) => {
  if (import.meta.env.DEV) {
    // 开发环境
    // 调用模拟支付的接口
    const res = await getMockPayAPI(id)
    if (res.code === '1') {
      // 支付成功,修改当前列表中的数据项
      const index = orderList.value.findIndex((item) => item.id === id)
      orderList.value[index].orderState = 2
      orderList.value[index].orderStateText = '待发货'
      // 提示用户支付成功
      uni.showToast({
        title: '支付成功',
        icon: 'success',
        mask: true,
      })
    }
  } else {
    // 生产环境
    // 调用微信支付的接口
    const res = await getWxPayAPI(id)
    // 弹出支付
    uni.requestPayment({
      provider: 'wxpay',
      orderInfo: '',
      ...res.result,
      success: (result) => {},
      fail: (error) => {},
    })
  }
}
// 确认收货按钮的回调
const ConfirmReceipt = (id: string) => {
  uni.showModal({
    title: '是否确认签收?',
    showCancel: true,
    success: async ({ confirm }) => {
      if (confirm) {
        // 确认签收
        const res = await putConfirmReceiptAPI(id)
        if (res.code === '1') {
          uni.showToast({
            title: '确认收货成功',
            icon: 'success',
            mask: true,
          })
          // 重新获取下数据
          tipText.value = '正在加载...'
          orderList.value = []
          getOrderListData(page.value, currentIndex.value)
        }
      }
    },
  })
}
// 删除订单按钮的回调
const deleteOrder = (id: string) => {
  // 二次询问用户
  uni.showModal({
    title: '是否删除订单?',
    showCancel: true,
    success: async ({ confirm, cancel }) => {
      if (confirm) {
        // 将列表中的数据移除
        orderList.value = orderList.value.filter((item) => item.id !== id)
        const res = await deleteOrderAPI([id])
        if (res.code === '1') {
          // 提示用户删除成功
          uni.showToast({
            title: '删除成功',
            icon: 'success',
          })
        }
      }
    },
  })
}
// 切换tabs栏的回调
const changeCurrentIndex = (index: number) => {
  currentIndex.value = index
}
// 取消订单
const cancel = async (id: string) => {
  const res = await cancelOrderAPI(id)
  console.log(res)
  if (res.code === '1') {
    page.value = 1
    getOrderListData(page.value, currentIndex.value)
  }
}
onShow(() => {
  tipText.value = '正在加载...'
  temp = 1
  orderList.value = []
  page.value = 1
  getOrderListData(page.value, currentIndex.value)
})
</script>

<style lang="scss">
page {
  height: 100%;
  overflow: hidden;
}

.viewport {
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: #fff;
}

// tabs
.tabs {
  display: flex;
  justify-content: space-around;
  line-height: 60rpx;
  margin: 0 10rpx;
  background-color: #fff;
  box-shadow: 0 4rpx 6rpx rgba(240, 240, 240, 0.6);
  position: relative;
  z-index: 9;

  .item {
    flex: 1;
    text-align: center;
    padding: 20rpx;
    font-size: 28rpx;
    color: #262626;
  }

  .cursor {
    position: absolute;
    left: 0;
    bottom: 0;
    width: 20%;
    height: 6rpx;
    // padding: 0 50rpx;
    background-color: #ff3304;
    /* 过渡效果 */
    transition: all 0.4s;
  }
}

// swiper
.swiper {
  display: flex;
  flex-direction: column;
  background-color: #f7f7f8;
  flex: 1;
}

// 订单列表
.orders {
  overflow-y: scroll;
  height: 100%;
  .card {
    min-height: 100rpx;
    padding: 20rpx;
    margin: 20rpx 20rpx 0;
    border-radius: 10rpx;
    background-color: #fff;

    &:last-child {
      padding-bottom: 40rpx;
    }
  }

  .status {
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 28rpx;
    color: #999;
    margin-bottom: 15rpx;

    .date {
      color: #666;
      flex: 1;
    }

    .primary {
      color: #ff9240;
    }

    .icon-delete {
      line-height: 1;
      margin-left: 10rpx;
      padding-left: 10rpx;
      border-left: 1rpx solid #e3e3e3;
    }
  }

  .goods {
    display: flex;
    margin-bottom: 20rpx;

    .cover {
      width: 170rpx;
      height: 170rpx;
      margin-right: 20rpx;
      border-radius: 10rpx;
      overflow: hidden;
      position: relative;
    }

    .quantity {
      position: absolute;
      bottom: 0;
      right: 0;
      line-height: 1;
      padding: 6rpx 4rpx 6rpx 8rpx;
      font-size: 24rpx;
      color: #fff;
      border-radius: 10rpx 0 0 0;
      background-color: rgba(0, 0, 0, 0.6);
    }

    .meta {
      flex: 1;
      display: flex;
      flex-direction: column;
      justify-content: center;
    }

    .name {
      height: 80rpx;
      font-size: 26rpx;
      color: #444;
    }

    .type {
      line-height: 1.8;
      padding: 0 15rpx;
      margin-top: 10rpx;
      font-size: 24rpx;
      align-self: flex-start;
      border-radius: 4rpx;
      color: #888;
      background-color: #f7f7f8;
    }

    .more {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 22rpx;
      color: #333;
    }
  }

  .payment {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    line-height: 1;
    padding: 20rpx 0;
    text-align: right;
    color: #999;
    font-size: 28rpx;
    border-bottom: 1rpx solid #eee;

    .quantity {
      font-size: 24rpx;
      margin-right: 16rpx;
    }

    .amount {
      color: #444;
      margin-left: 6rpx;
    }

    .symbol {
      font-size: 20rpx;
    }
  }

  .action {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    padding-top: 20rpx;

    .button {
      width: 180rpx;
      height: 60rpx;
      display: flex;
      justify-content: center;
      align-items: center;
      margin-left: 20rpx;
      border-radius: 60rpx;
      border: 1rpx solid #ccc;
      font-size: 26rpx;
      color: #444;
    }

    .secondary {
      color: #ff3304;
      border-color: #ff3304;
    }

    .primary {
      color: #fff;
      background-color: #ff3304;
    }
  }

  .loading-text {
    text-align: center;
    font-size: 28rpx;
    color: #666;
    padding: 20rpx 0;
  }
}
</style>
